"""
学员详细信息API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import func

from app.database import get_db
from app.models.student import Student
from app.models.order import Order
from app.models.course import Course, CourseStage
from app.models.subject import Subject
from app.models.progress import StudentProgress
from app.models.assignment import StudentCourseAssignment
from app.models.team import Team, EmployeeTeam
from app.api.deps import get_current_active_user
from app.models.employee import Employee

router = APIRouter()


@router.get("/{student_id}/detail")
def get_student_detail(
    student_id: int,
    db: Session = Depends(get_db),
    current_user: Employee = Depends(get_current_active_user)
) -> Any:
    """
    获取学员详细信息，包括课程和阶段信息
    """
    # 获取学员基本信息
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学员不存在"
        )
    
    # 获取学员的所有订单
    orders = db.query(Order).filter(Order.student_id == student_id).all()
    
    # 构建订单详细信息
    order_details = []
    for order in orders:
        # 获取课程信息
        course = db.query(Course).filter(Course.id == order.course_id).first()
        if not course:
            continue
            
        # 获取科目信息
        subject = db.query(Subject).filter(Subject.id == course.subject_id).first()
        
        # 获取课程阶段信息
        stages = db.query(CourseStage).filter(
            CourseStage.course_id == course.id
        ).order_by(CourseStage.stage_number).all()
        
        # 获取学员在这个课程的学习进度
        progress_records = db.query(StudentProgress).filter(
            StudentProgress.student_id == student_id,
            StudentProgress.course_id == course.id
        ).all()
        
        # 创建进度映射
        progress_map = {p.stage_number: p for p in progress_records}
        
        # 获取课程分配信息（报名时间）
        assignment = db.query(StudentCourseAssignment).filter(
            StudentCourseAssignment.student_id == student_id,
            StudentCourseAssignment.course_id == course.id,
            StudentCourseAssignment.order_id == order.id
        ).first()
        
        # 构建阶段信息
        stage_details = []
        for stage in stages:
            progress = progress_map.get(stage.stage_number)
            stage_details.append({
                "id": stage.id,
                "stage_number": stage.stage_number,
                "stage_name": stage.stage_name,
                "stage_price": float(stage.stage_price),
                "description": stage.description,
                "progress": {
                    "status": progress.status if progress else "not_started",
                    "progress_percentage": float(progress.progress_percentage) if progress else 0.0,
                    "start_date": progress.start_date.isoformat() if progress and progress.start_date else None,
                    "end_date": progress.end_date.isoformat() if progress and progress.end_date else None
                } if progress else {
                    "status": "not_started",
                    "progress_percentage": 0.0,
                    "start_date": None,
                    "end_date": None
                }
            })
        
        # 获取相关员工信息
        sales_employee = None
        sales_team_leader = None
        if order.sales_employee_id:
            sales_emp = db.query(Employee).filter(Employee.id == order.sales_employee_id).first()
            if sales_emp:
                sales_employee = {
                    "id": sales_emp.id,
                    "name": sales_emp.name,
                    "employee_no": sales_emp.employee_no,
                    "position": sales_emp.position
                }
                
                # 获取售前员工的团队负责人
                team_assignment = db.query(EmployeeTeam).filter(
                    EmployeeTeam.employee_id == sales_emp.id,
                    EmployeeTeam.status == "active"
                ).first()
                
                if team_assignment:
                    team = db.query(Team).filter(Team.id == team_assignment.team_id).first()
                    if team and team.leader_id:
                        team_leader = db.query(Employee).filter(Employee.id == team.leader_id).first()
                        if team_leader:
                            sales_team_leader = {
                                "id": team_leader.id,
                                "name": team_leader.name,
                                "employee_no": team_leader.employee_no,
                                "position": team_leader.position
                            }
        
        reception_employee = None
        if order.reception_employee_id:
            reception_emp = db.query(Employee).filter(Employee.id == order.reception_employee_id).first()
            if reception_emp:
                reception_employee = {
                    "id": reception_emp.id,
                    "name": reception_emp.name,
                    "employee_no": reception_emp.employee_no,
                    "position": reception_emp.position
                }
        
        order_details.append({
            "id": order.id,
            "order_no": order.order_no,
            "course": {
                "id": course.id,
                "name": course.name,
                "total_stages": course.total_stages,
                "total_price": float(course.total_price),
                "description": course.description,
                "status": course.status,
                "subject": {
                    "id": subject.id if subject else None,
                    "name": subject.name if subject else None
                } if subject else None
            },
            "stages": stage_details,
            "payment_method": order.payment_method,
            "registration_type": order.registration_type,
            "should_pay_amount": float(order.should_pay_amount),
            "actual_pay_amount": float(order.actual_pay_amount),
            "order_date": order.order_date.isoformat() if order.order_date else None,
            "enrollment_date": assignment.enrollment_date.isoformat() if assignment and assignment.enrollment_date else None,
            "status": order.status,
            "sales_employee": sales_employee,
            "sales_team_leader": sales_team_leader,
            "reception_employee": reception_employee,
            "performance_source": order.performance_source,
            "assignment": {
                "enrollment_date": assignment.enrollment_date.isoformat() if assignment and assignment.enrollment_date else None,
                "contract_status": assignment.contract_status if assignment else None,
                "status": assignment.status if assignment else None
            } if assignment else None
        })
    
    # 计算总统计信息
    total_orders = len(orders)
    total_paid = sum(float(order.actual_pay_amount) for order in orders if order.status == "paid")
    total_should_pay = sum(float(order.should_pay_amount) for order in orders)
    
    return {
        "student": {
            "id": student.id,
            "name": student.name,
            "gender": student.gender,
            "phone": student.phone,
            "email": student.email,
            "province": student.province,
            "source": student.source,
            "status": student.status,
            "created_at": student.created_at.isoformat() if student.created_at else None,
            "updated_at": student.updated_at.isoformat() if student.updated_at else None
        },
        "orders": order_details,
        "statistics": {
            "total_orders": total_orders,
            "total_should_pay": total_should_pay,
            "total_paid": total_paid,
            "unpaid_amount": total_should_pay - total_paid
        }
    }


@router.get("/{student_id}/courses")
def get_student_courses(
    student_id: int,
    db: Session = Depends(get_db),
    current_user: Employee = Depends(get_current_active_user)
) -> Any:
    """
    获取学员报名的所有课程
    """
    # 获取学员的所有订单
    orders = db.query(Order).filter(Order.student_id == student_id).all()
    
    courses = []
    for order in orders:
        course = db.query(Course).filter(Course.id == order.course_id).first()
        if course:
            subject = db.query(Subject).filter(Subject.id == course.subject_id).first()
            courses.append({
                "course_id": course.id,
                "course_name": course.name,
                "subject_name": subject.name if subject else None,
                "total_price": float(course.total_price),
                "order_no": order.order_no,
                "order_status": order.status,
                "paid_amount": float(order.actual_pay_amount)
            })
    
    return {"courses": courses}


@router.get("/{student_id}/stages/{course_id}")
def get_student_course_stages(
    student_id: int,
    course_id: int,
    db: Session = Depends(get_db),
    current_user: Employee = Depends(get_current_active_user)
) -> Any:
    """
    获取学员特定课程的阶段信息
    """
    # 验证学员是否有这个课程的订单
    order = db.query(Order).filter(
        Order.student_id == student_id,
        Order.course_id == course_id
    ).first()
    
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学员没有报名此课程"
        )
    
    # 获取课程阶段
    stages = db.query(CourseStage).filter(
        CourseStage.course_id == course_id
    ).order_by(CourseStage.stage_number).all()
    
    stage_details = []
    for stage in stages:
        stage_details.append({
            "id": stage.id,
            "stage_number": stage.stage_number,
            "stage_name": stage.stage_name,
            "stage_price": float(stage.stage_price),
            "description": stage.description
        })
    
    return {
        "course_id": course_id,
        "order_no": order.order_no,
        "stages": stage_details
    }
